<head>
    <script type="text/javascript" src="./jquery.js"></script>
    <script type="text/javascript">
        jQuery(document).ready(function(){
            jQuery("form[name=frmRegister] input[name=txtUserName]").blur(function(){
                jQuery.ajax({
                    type:"GET",
                    data:"key="+$("form[name=frmRegister] input[name=txtUserName]").val(),
                    url:"check_exist.php?type=1",
                    success:function(result){
                        $("#spAvailability").html(result);
                    }
                });
            });
        });
        jQuery(document).ready(function(){
            jQuery("form[name=frmRegister] input[name=txtEmail]").blur(function(){
                jQuery.ajax({
                    type:"GET",
                    data:"key="+$("form[name=frmRegister] input[name=txtEmail]").val(),
                    url:"check_exist.php?type=2",
                    success:function(result){
                        $("#spEmailAvailability").html(result);
                    }
                });
            });
        });
        function check_Validation()
        {
            var error = "";
            if(frmRegister.txtUserName.value =="")
                error += "* User name is mandatory\n";
            else
                if(! /^[a-z0-9]+$/gi.test(frmRegister.txtUserName.value))
                    error += "* User Name can only alphanumeric\n";
            if(frmRegister.txtEmail.value =="")
                error += "* Email is mandatory\n";
            else
                if(! /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(frmRegister.txtEmail.value))
                    error += "* Email isn't correct format\n";
            if(frmRegister.txtPassword.value =="")
                error += "* Password is mandatory\n";
            else
                if(! (/[\d]/g.test(frmRegister.txtPassword.value) && /[a-z]/gi.test(frmRegister.txtPassword.value)))
                    error += "* Password must have  both letters and numbers\n";
            if(frmRegister.txtPassword.value != frmRegister.txtRePassword.value)
                error += "* Password and Repassword not macth\n";
            if(frmRegister.txtFullName.value=="")
                error +="* Full name is mandatory\n";
            else if(frmRegister.txtFullName.value.length<=6){
                error +="* Full name must have more than 6 characters\n";
            }
            if(frmRegister.txtBirthday.value != "")
            {
                var flag = true;
                try
                {
                    var value = frmRegister.txtBirthday.value.split('/');
                    if(value.length > 3)
                        flag = false;
                    else
                        if(value[0].length != 2 || value[1].length != 2 || value[3].length != 4)
                            flag = false;
                    else
                    {
                        var d = pasrtInt(value[0]);
                        var m = pasrtInt(value[1]);
                        var y = pasrtInt(value[2]);
                        if(d<1 || d> 31|| m<1||m>12|| y<1900 || y> 2010)
                            flag = false;
                    }
                }
                catch(e)
                {
                    flag = false;
                }
                if(!flag)
                    error += "* Ivalid datetime format in Birthday\n";
            }
            else
                if(frmRegister.txtPhone.value!="" && ! /[\d]{1,3}-[\d]{1,3}-[\d]{7}/g.test(frmRegister.txtPhone.value)){
                    error+="* Invalid phone number format\n"
                }
            if(error!=""){
                alert("Please fix the following errors:\n"+error);
                return false;
            }
            else
            {
                checkExist(frmRegister.txtUserName.value, frmRegister.txtEmail.value);
            }
            return true;
        }
         
    </script>
</head>
<body>
    <?php
    require 'connect.inc';
    require 'session.inc';
    $res = "";
    $state = 0;
    if ($_SESSION["isLogin"] == 1)
        $state = 1;
    if (isset($_REQUEST["btnSubmit"])) {
        $username = $_REQUEST["txtUserName"];
        $email = $_REQUEST["txtEmail"];
        $pass = md5($_REQUEST["txtPassword"]);
        $fullname = $_REQUEST["txtFullName"];
        $birthday = $_REQUEST["txtBirthday"];
        $phone = $_REQUEST["txtPhone"];
        $country = $_REQUEST["Countries"];
        $department = $_REQUEST["Department"];
        if ($birthday == "")
            $birthday = "NULL";
        else
            $birthday = "'" . $birthday . "'";
        if ($phone == "")
            $phone = "NULL";
        else
            $phone = "'" . $phone . "'";
        $r1 = mysql_query("SELECT * FROM USERS WHERE user_name = '$username'");
        $r2 = mysql_query("SELECT * FROM USERS WHERE email = '$email'");
        if ($r1 && mysql_num_rows($r1) < 1 && $r2 && mysql_num_rows($r2) < 1) {
            $strSQL = "INSERT INTO USERS(user_name,email,password,full_name,birthday,phone,signup_date,department_id,country_id)
					VALUES('$username','$email','$pass','$fullname',$birthday,$phone,now(),$country,$department)";

            $result = mysql_query($strSQL);
            if ($result) {
                $state = 1;
                $_SESSION["isLogin"] = 1;
                $_SESSION["username"] = $username;
                $_SESSION["fullName"] = $fullname;
                $_SESSION["email"] = $email;
            }
        }
    } else {
        $username = "";
        $email = "";
        $fullname = "";
        $birthday = "";
        $phone = "";
    }
    if ($state == 0) {
         if ($birthday == "NULL")
            $birthday = "";
        if ($phone == "NULL")
            $phone = "";
        else
            $phone = "'" . $phone . "'";
        $strSQL = "SELECT * FROM countries";
        $result = mysql_query($strSQL);
        $cboCountry = "<select name='Countries'>";
        if ($result)
            while ($row = mysql_fetch_array($result)) {
                $id = $row["country_id"];
                $name = $row["country_name"];
                $cboCountry .= "<option value='$id'>$name</option>";
            }
        $cboCountry .= "</select>";
        $strSQL = "SELECT * FROM departments";
        $result = mysql_query($strSQL);
        $cboDepartment = "<select name='Department'>";
        if ($result)
            while ($row = mysql_fetch_array($result)) {
                $id = $row["department_id"];
                $name = $row["department_name"];
                $cboDepartment .= "<option value='$id'>$name</option>";
            }
        $cboDepartment .= "</select>";
        $res = "<a href='register.php'>Register</a>
        |
        <a href='login.php'>Login</a>
        <hr>
        <form onsubmit='return check_Validation();' action='register.php' method='POST' name='frmRegister'>
            User name:
            <input type='text' name='txtUserName' value='$username'>
            <span id='spAvailability' style='color: red'>
                <font style='color:red'></font>
           </span>
            <br>
            Email:
            <input type='text' name='txtEmail' value='$email'>
            <span id='spEmailAvailability' style='color: red'>
                <font style='color:red'></font>
           </span>
            <br>
            Password:
            <input type='password' name='txtPassword'>
            <br>
            Re-type password:
            <input type='password' name='txtRePassword'>
            <br>
            Full name:
            <input type='text' name='txtFullName' value='$fullname'>
            <br>
            Birthday (dd/mm/yyyy):
            <input type='text' name='txtBirthday' value='$birthday'>
            <br>
            Phone (<country_code>-<area_code>-<phone_number>):
                        <input type='text' name='txtPhone' value='$phone'>
                        <br>
                        Country:" . $cboCountry . "
                        <br>
                        Department:" . $cboDepartment . "
                        <br>
                        <input type='submit' name='btnSubmit' value='Submit'>
                        <input type='reset' name='btnCancel' value='Cancel'>
                        </form>";
        echo $res;
    } else {
        header("Location: login.php");
    }
    ?>

</body>
